package com.lx.config;

import com.lx.filter.JwtAuthenticationTokenFilter;
import com.lx.service.impl.JwtUserDetailsServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author 段誉
 * @create 2019-06-26 13:47
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  /**
   * Spring会自动寻找同样类型的具体类注入，这里就是JwtUserDetailsServiceImpl了
   */
  private UserDetailsService userDetailsService;
  @Autowired
  public WebSecurityConfig(JwtUserDetailsServiceImpl jwtUserDetailsService) {
    this.userDetailsService = jwtUserDetailsService;
  }

  @Autowired
  public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder,
                                      PasswordEncoder passwordEncoder) throws Exception {
    authenticationManagerBuilder
            // 设置UserDetailsService
            .userDetailsService(this.userDetailsService)
            // 使用BCrypt进行密码的hash
            .passwordEncoder(passwordEncoder);
  }

  /**
   * 装载BCrypt密码编码器
   * @return
   */
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // 由于使用的时JWT，这里就不需要csrf
      .csrf().disable()
      // 基于token，所以不需要session
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
      .authorizeRequests()
      //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
      // 允许对于网站静态资源的无授权访问
      .antMatchers(
              HttpMethod.GET,
              "/",
              "/*.html",
              "/favicon.ico",
              "/**/*.html",
              "/**/*.css",
              "/**/*.js"
      ).permitAll()
      // 对于获取token的rest api要允许匿名访问
      .antMatchers("/auth/**").permitAll()
      // 除上面外的所有请求全部需要鉴权认证
      .anyRequest().authenticated();
    //禁用缓存
    http.headers().cacheControl();

    http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
  }

  @Bean
  public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
    return new JwtAuthenticationTokenFilter();
  }

  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}
